// pages/apply/apply.js
const app = getApp();
import { deviceFindAll,deviceFind,refresh,control,timeSet,deviceUpdate,getState,cameraControl } from "../../public/api/device.js"
import { throttle,formatTime } from "../../utils/util.js";
const md5 = require('../../utils/md5')
const secretKey = 'ZSHBZ-EPW3Q-J7Y5T-4Z3UP-27E7J-ZVBCP'
const SK = 'PoyKe8pPMu7DclpJhst166WJHFOTzwnJ'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeColor: '#509222',
    translations: {},
    language: '',
    longitude: '',  // 经度
    latitude: '',    // 纬度
    scale: 14,              // 缩放级别
    markers: [{
      id: 1,
      latitude: '',
      longitude: '',
      title: '标记点',
      width: 50,  // 图标的宽度
      height: 50  // 图标的高度
    }],
    name: '',
    deviceList: [],
    deviceInfo: {},
    currentUuid: '',
    userType: '',
    hideModal: true, 
    hideModalDevice: true,
    hideModalTime: true,
    hideModalEditDevice: true,
    selectStartTime: '09:00',
    selectEndTime: '18:00',
    step: 1,
    currentTimer: 1,
    startTime1: '',
    endTime1: '',
    startTime2: '',
    endTime2: '',
    startTime3: '',
    endTime3: '',
    startTime4: '',
    endTime4: '',
    startTime: '',
    endTime: '',
    deviceToken: '',
    cameraStream: '',
    timer: '',
    address: '',
    recommend: '',
    newName: '',
    showTv: true,
    switch1Checked: false,
    switch2Checked: false,
    switch3Checked: false,
    switch4Checked: false,
    time: 60
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let switch1Checked = wx.getStorageSync('switch1Checked') ? true : false
    let switch2Checked = wx.getStorageSync('switch2Checked') ? true : false
    let switch3Checked = wx.getStorageSync('switch3Checked') ? true : false
    this.setData({
      switch1Checked,
      switch2Checked,
      switch3Checked
    })
  },

  // 获取配置文件状态
  getState() {
    getState().then(res => {
      if(res.data.code === 1) {
        this.setData({showTv: res.data.data})
      }
    })
  },

  // 获取位置
  getLocation(latitude,longitude) {
    let that = this
    let locat = this.bd09ToGcj02(longitude,latitude)
    let parameters = {
      key: secretKey,
      location: `${locat.lat},${locat.lng}`
    }
    let sig = this.generateSignature(parameters, secretKey);
    wx.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1?key=${parameters.key}&location=${parameters.location}&sig=${sig}`, 
      method: 'GET',
      success: res => {
        console.log(111,res); // 此处返回的就是城市名称
        that.setData({
          address: res.data.result ? res.data.result.address : '',
          recommend: res.data.result ? res.data.result.formatted_addresses.recommend : '',
        })
      },
      fail: err => {
        console.error(222,err);
      }
    })
  },

  // 坐标系转换
  bd09ToGcj02(bdLng, bdLat) {
    const x = bdLng - 0.0065;
    const y = bdLat - 0.006;
    // 通过更精确的调整系数来减少偏差
    const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);
    const theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);
    // 更精确的坐标计算
    const gcjLng = z * Math.cos(theta);
    const gcjLat = z * Math.sin(theta);
    // 返回转换后的GCJ-02坐标
    return {
      lng: gcjLng,
      lat: gcjLat
    };
  },

  generateSignature(params) {
    let paramsArray = [];
    for (let param in params) {
      if (params.hasOwnProperty(param)) {
        paramsArray.push(param + '=' + params[param]);
      }
    }
    // 确保参数按字典顺序排序
    paramsArray.sort();
    let stringToSign = paramsArray.join('&');
    // 在 stringToSign 前面添加额外的内容
    let prefix = "/ws/geocoder/v1?"; // 这里替换为你想要添加的前缀
    stringToSign = prefix + stringToSign + SK;
    console.log(stringToSign);
    return md5.hexMD5(stringToSign); // 计算 MD5 值
  },

  // 刷新设备
  doRefresh() {
    let data = {}
    data.uuid = this.data.deviceInfo.uuid
    wx.showLoading({
      title: '处理中',
    })
    refresh(data).then(res => {
      if(res.data.code === 1) {
        wx.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1000,
          success() {
            setTimeout(() => {
              wx.hideLoading()
            }, 1000)
          }
        })
        wx.hideLoading()
        let deviceInfo = res.data.data
        let locat = this.bd09ToGcj02(deviceInfo.longitude,deviceInfo.latitude)
        this.setData({
          deviceInfo,
          latitude: deviceInfo.latitude,
          longitude: deviceInfo.longitude,
          switch4Checked: deviceInfo.lighting == 1 ? true : false,
          markers: [{
            id: 1,
            latitude: locat.lat,
            longitude: locat.lng,
            title: '标记点',
            width: 50,  // 图标的宽度
            height: 50  // 图标的高度
          }],
        })
        // this.getLocation()
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  // 开关设备
  doControl: throttle(function(e) {
    let type = e.currentTarget.dataset.type
    let data = {}
    data.uuid = this.data.deviceInfo.uuid
    data.type = type
    wx.showLoading({
      title: '处理中',
    })
    control(data).then(res => {
      if(res.data.code === 1) {
        if(type == 1) {
          wx.showToast({
            title: '设备开启成功',
            icon: 'success',
            duration: 1000,
            success() {
              setTimeout(() => {
                wx.hideLoading()
              }, 1000)
            }
          })
        } else {
          wx.showToast({
            title: '设备关闭成功',
            icon: 'success',
            duration: 1000,
            success() {
              setTimeout(() => {
                wx.hideLoading()
              }, 1000)
            }
          })
        } 
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  }),

  goAddDevice() {
    wx.navigateTo({
      url: '/packageMyInfo/pages/device/device',
    })
  },

  getDeviceList() {
    let data = {}
    data.uuid = ''
    deviceFindAll(data).then(res => {
      if(res.data.code === 1) {
        if(res.data.data && res.data.data.length) {
          let obj = res.data.data[0]
          this.setData({
            deviceList: res.data.data
          })
          if(wx.getStorageSync('currentDevice')) {
            let device = wx.getStorageSync('currentDevice')
            this.setData({
              currentUuid: device.uuid,
              userType: device.userType,
            })
          } else {
            this.setData({
              currentUuid: obj.uuid,
              userType: obj.userType
            })
            wx.setStorageSync('currentDevice', obj)
          }
          this.getDeviceDetail()
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  getDeviceDetail() {
    let data = {}
    data.uuid = this.data.currentUuid
    deviceFind(data).then(res => {
      if(res.data.code === 1) {
        let deviceInfo = res.data.data
        deviceInfo.offlineTime = deviceInfo.offlineTime ? formatTime(new Date(deviceInfo.offlineTime)) : ''
        deviceInfo.online = this.data.deviceList.find(v => v.uuid === this.data.currentUuid).online
        let locat = this.bd09ToGcj02(deviceInfo.longitude,deviceInfo.latitude)
        console.log(locat)
        this.setData({
          name: deviceInfo.deviceName,
          deviceInfo,
          latitude: deviceInfo.latitude,
          longitude: deviceInfo.longitude,
          switch4Checked: deviceInfo.lighting == 1 ? true : false,
          markers: [{
            id: 1,
            latitude: locat.lat,
            longitude: locat.lng,
            title: '标记点',
            width: 50,  // 图标的宽度
            height: 50  // 图标的高度
          }],
        })
        // this.getLocation(deviceInfo.latitude, deviceInfo.longitude)
        if(res.data.data.timeList != null && res.data.data.timeList != "[]") {
          let timeList = JSON.parse(res.data.data.timeList)
          this.setData({
            startTime1: timeList[0].beginTime,
            endTime1: timeList[0].endTime,
            startTime2: timeList[1].beginTime,
            endTime2: timeList[1].endTime,
            startTime3: timeList[2].beginTime,
            endTime3: timeList[2].endTime
          })
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  chooseDevice(e) {
    let { uuid,name,userType } = e.currentTarget.dataset
    this.setData({
      currentUuid: uuid,
      name,
      userType
    })
    this.getDeviceDetail()
  },

  openDeviceModal(e) {
    let id = e.currentTarget.dataset.id
    if(id === 'device') {
      // this.setData({
      //   hideModalDevice: !this.data.hideModalDevice
      // })
      wx.navigateTo({
        url: '/packageMyInfo/pages/device/device'
      })
    } else if(id === 'editdevice') {
      this.setData({
        newName: this.data.name,
        hideModalEditDevice: false
      })
    }
  },

  hideDeviceModal(e) {
    let id = e.currentTarget.dataset.id
    if(id === 'device') {
      this.setData({hideModalDevice: true})
    } else if(id === 'editdevice') {
      this.setData({
        hideModalEditDevice: true,
        newName: ''
      })
    }
    
  },

  onMarkerTap(e) {
    const { latitude, longitude } = this.data.markers[0]; // 获取标记点坐标
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      scale: 18,
      // name: this.data.address,
      // address: this.data.recommend
    });
  },

  openTimerDialog(e) {
    this.setData({
      currentTimer: e.currentTarget.dataset.id,
      hideModalTime: false
    })
  },

  hideModalTime() {
    this.setData({
      hideModalTime: true,
      step: 1,
      selectTime: '09:00',
    })
  },

  doSelectTime() {
    this.setData({
      ["startTime" + this.data.currentTimer]: this.data.selectStartTime,
      ["endTime" + this.data.currentTimer]: this.data.selectEndTime,
      hideModalTime: true
    })
    this.doTimeSet()
  },

  // 设备定时
  doTimeSet() {
    let data = {}
    data.uuid = this.data.deviceInfo.uuid
    data.times = [
      {beginTime: this.data.startTime1, endTime: this.data.endTime1},
      {beginTime: this.data.startTime2, endTime: this.data.endTime2},
      {beginTime: this.data.startTime3, endTime: this.data.endTime3},
    ]
    timeSet(data).then(res => {
      if(res.data.code === 1) {
        wx.showToast({
          title: '设置成功',
          icon: 'success'
        })
        this.getDeviceDetail()
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  onInput(e) {
    console.log(e);
    let id = e.currentTarget.dataset.id
    if(id == 'start') {
      this.setData({selectStartTime: e.detail})
    } else if(id == 'end') {
      this.setData({selectEndTime: e.detail})
    }
  },

  // 打开视频流
  openVideoModel() {
    let that = this
    // that.getDeviceToken()
    let info = {
      accessToken: 'at.ap1qvh5a2q6lh0jk16smcnzz4qyaf4wa-92q4oiucom-0py8h4k-glneqwz8c',
      deviceSerial: 'AW6830223',
      channelNo: 1
    }
    wx.navigateToMiniProgram({
      appId: 'wxf2b3a0262975d8c2',
      path: 'pages/live/live?accessToken=' + info.accessToken + '&deviceSerial=' + info.deviceSerial+'&channelNo=' + info.channelNo,
      success(res) {
        // 打开成功
        console.log(res);
      }
    })
    // this.setData({hideModal: false})
  },

  openVideoModel2() {
    let outerChain = 'https://www.wxidev.top/live/index.html?sn=' + this.data.currentUuid
    wx.navigateTo({
      url: '/packageApply/pages/outer/outer?src=' + encodeURIComponent(outerChain),
    })
    return
    let data = {}
    wx.navigateTo({
      url: '/packageApply/pages/live2/live2?id=' + this.data.currentUuid
    })
    return
    data.uuid = this.data.currentUuid
    data.style = 'on'
    cameraControl(data).then(res => {
      if(res.data.code === 1) {
        let time = 60
        let timer = setInterval(() => {
          wx.showLoading({
            title: `加载中(${time})` ,
            mask: true
          })
          time--
          if(time <= 0) {
            clearInterval(timer)
            wx.hideLoading()
            wx.navigateTo({
              url: '/packageApply/pages/live2/live2?id=' + this.data.currentUuid
            })
          }
        },1000)
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
   
  },

  closeVideo() {
    let that = this
    let data = {
      channel: '0',
      stream: '1',
      username: "admin",
      password: "13579abc",
    }
    app.globalData.api.closeLivestream(data,that.data.deviceToken,(result)=>{
      console.log('关闭视频流：',result);
    })
    this.setData({hideModal: true})
    // clearInterval(this.data.timer)
  },

  doHandle: throttle(function(e) {
    let style = e.currentTarget.dataset.id
    let that = this
    if(style == 'on') {
      that.doCameraControl(that.data.currentUuid, style)
      let time = 60
      let timer = setInterval(() => {
        wx.showLoading({
          title: `加载中(${time}s)` ,
          mask: true
        })
        time--
        if(time < 0) {
          clearInterval(timer)
          wx.hideLoading()
          that.openVideoModel2()
        }
      },1000)
    } else if(style == 'off') {
      that.doCameraControl(that.data.currentUuid, style)
    }
  }, 1500),

  // 修改摄像头状态
  doCameraControl(id, style) {
    let data = {}
    data.uuid = id ? id : this.data.deviceSerial
    data.style = style
    cameraControl(data).then(res => {
      if(res.data.code === 1) {
        this.getDeviceDetail()
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  // 编辑设备
  doEditDevice() {
    let that = this
    if(this.data.newName === '') {
       wx.showToast({
        title: '请输入设备名称',
        icon: 'none'
      })
      return false
    }
    let data = {}
    data.uuid = this.data.currentUuid
    data.name = this.data.newName
    deviceUpdate(data).then(res => {
      if(res.data.code === 1) {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1500,
          success() {
            that.getDeviceList()
            that.setData({
              hideModalEditDevice: true,
              newName: ''
            })
          }
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  // 数量统计
  goStatistics() {
    wx.navigateTo({
      url: '/packageApply/pages/statistics/statistics?uuid=' + this.data.currentUuid
    })
  },

  switchChange(e) {
    let that = this
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    console.log(e);
    if(index == 1) {
      wx.setStorageSync('switch1Checked',value)
      let data = {}
      data.uuid = this.data.deviceInfo.uuid
      data.type = value ? 1 : -1
      wx.showLoading({
        title: '处理中',
      })
      control(data).then(res => {
        if(res.data.code === 1) {
          if(data.type == 1) {
            wx.showToast({
              title: '设备开启成功',
              icon: 'success',
              duration: 1000,
              success() {
                setTimeout(() => {
                  wx.hideLoading()
                }, 1000)
              }
            })
          } else {
            wx.showToast({
              title: '设备关闭成功',
              icon: 'success',
              duration: 1000,
              success() {
                setTimeout(() => {
                  wx.hideLoading()
                }, 1000)
              }
            })
          } 
          this.getDeviceDetail()
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      })
    } else if(index == 2) {
      wx.setStorageSync('switch2Checked',value)
    } else if(index == 3) {
      wx.setStorageSync('switch3Checked',value)
    } else if(index == 4) {
      if(value) {
        that.doCameraControl(that.data.currentUuid, 'on')
        let time = 60
        let timer = setInterval(() => {
          wx.showLoading({
            title: `加载中(${time}s)` ,
            mask: true
          })
          time--
          if(time < 0) {
            clearInterval(timer)
            wx.hideLoading()
            that.openVideoModel2()
          }
        },1000)
      } else {
        that.doCameraControl(that.data.currentUuid, 'off')
      }
    }
  },

  doStop() {
    return false
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const translations = app.globalData.translations;
    let language = wx.getStorageSync('language')
    this.setData({
      language,
      translations
    });
    this.getState()
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1,
        list: translations.list
      });
    }
    this.getDeviceList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})